<template>
  <div>
  <div>
    <el-row type="flex" justify="center" align="middle" class="licc-personal-content-row">
      <el-row type="flex" justify="center" align="middle" style="width: 1100px;height: 50px;background-color: #fff">
        <el-col class="licc-center-title">
          <em>我的信息</em>
        </el-col>
      </el-row>
    </el-row>
    <el-row type="flex" justify="center" align="middle" class="licc-personal-content-row">
      <el-row type="flex" justify="center" style="width: 1100px;background-color: #fff">
        <el-col :span="12" style="border-right: 1px solid #bbb;">
          <el-row>
            <el-col>
              <div class="licc-personal-info-top">个人信息</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <div class="licc-personal-info-title">
                <em>头像：</em>
              </div>
              <div class="licc-personal-info-value">
                <el-image style="width:100px; height:100px" :src="userInfo.photo"></el-image>
              </div>
              <div style="float: left;margin-top: 100px;padding-left: 10px">
                  <em class="licc-personal-info-image-update"
                    @click="updatePhoto"><i class="el-icon-edit"></i>修改头像</em>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <div class="licc-personal-info-title">
                <em>手机：</em>
              </div>
              <div class="licc-personal-info-value">
                <!--<el-input v-model="userInfo.phone" placeholder="暂无"></el-input>-->
                <em>{{userInfo.phone}}</em>
              </div>
              <!--<div class="licc-personal-info-value">-->
                <!--<i class="el-icon-edit"></i>-->
                <!--<em style="font-size: 10px; color: #999">更换手机号</em>-->
              <!--</div>-->
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <div class="licc-personal-info-title">
                <em>昵称：</em>
              </div>
              <div class="licc-personal-info-value">
                <el-form :model="userInfo" ref="userInfo">
                  <el-form-item prop="nickname"
                                :rules="[{trigger: 'blur', validator: validateNickname}]"
                                style="margin-bottom: 0px;">
                    <el-input name="nickname" v-model="userInfo.nickname" placeholder="暂无"></el-input>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <div class="licc-personal-info-title">
                <em>性别：</em>
              </div>
              <div class="licc-personal-info-value">
                <el-radio-group v-model="userInfo.sex">
                  <el-radio :label="0">保密</el-radio>
                  <el-radio :label="1">男</el-radio>
                  <el-radio :label="2">女</el-radio>
                </el-radio-group>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <div class="licc-personal-info-title">
                <em>生日：</em>
              </div>
              <div class="licc-personal-info-value">
                <el-date-picker
                  v-model="userInfo.age"
                  type="date"
                  :picker-options="pickerOptions"
                  :clearable="false"
                  value-format="yyyy-MM-dd HH:mm:SS"
                  placeholder="保密">
                </el-date-picker>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <div class="licc-personal-info-title" style="padding-left: 80px">
                <el-button type="danger" @click="userInfoSubmit('userInfo')" style="width: 130px">保 存 <svg-icon icon-class="user_info_save"/></el-button>
              </div>
            </el-col>
          </el-row>
        </el-col>

        <el-col :span="12">
          <el-row>
            <el-col>
              <div class="licc-personal-info-top">收货地址信息</div>
            </el-col>
          </el-row>
          <el-row
            v-for="(item, index) in addressInfos"
            :key="item.id">
            <el-col class="licc-personal-address">
              <div class="licc-personal-address-consignee">{{item.consignee}}</div>
              <div class="licc-personal-address-phone">{{item.phone}}</div>
              <div class="licc-personal-address-click">
                <i @click="updateAddress(item)" class="el-icon-edit"></i>
                <i @click="deleteAddress(item)" class="el-icon-delete"></i>
              </div>
              <div class="licc-personal-address-info">{{item.provinceName}}{{item.cityName}}{{item.districtName}}{{item.streetName}} - {{item.address}}</div>
            </el-col>
          </el-row>
          <el-row>
            <el-col class="licc-personal-address">
              <el-button type="danger" @click="addressInfoAdd" style="width: 130px">添 加 <svg-icon icon-class="user_info_save"/></el-button>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-row>
  </div>
  <div>
    <el-dialog
      title="添加地址"
      :visible.sync="addressDialogVisible"
      width="900px"
      :before-close="handleClose">
      <span>
        <el-form :model="addressInfo" ref="addressInfo" label-width="55px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="省级">
                <el-select value-key="name" v-model="province" filterable @change="changeAddress(1)">
                  <el-option
                    v-for="(item,index) in provinces"
                    :key="item.name+index"
                    :label="item.name"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="市级">
                <el-select value-key="name" v-model="city" :disabled="disabledCity" filterable @change="changeAddress(2)">
                  <el-option
                    v-for="(item,index) in cities"
                    :key="item.name+index"
                    :label="item.name"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="县级">
                <el-select value-key="name" v-model="district" :disabled="disabledDistrict" filterable @change="changeAddress(3)">
                  <el-option
                    v-for="(item,index) in districts"
                    :key="item.name+index"
                    :label="item.name"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="乡镇">
                <el-select value-key="name" v-model="street" :disabled="disabledStreet" filterable @change="changeAddress(4)">
                  <el-option
                    v-for="(item,index) in streets"
                    :key="item.name+index"
                    :label="item.name"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item
                label="收货人"
                prop="consignee"
                :rules="[{trigger: 'blur', validator: validateConsignee}]">
                <el-input name="consignee" v-model="addressInfo.consignee" placeholder="收货人名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="手机"
                prop="phone"
                :rules="[{trigger: 'blur', validator: validateAddressPhone}]">
                <el-input name="phone" v-model="addressInfo.phone" placeholder="收货人联系电话"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="详址"
                prop="address"
                :rules="[{trigger: 'blur', validator: validateAddressInfo}]">
                <el-input name="address" v-model="addressInfo.address" placeholder="收货人详细地址"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addressDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addressInfoSave">保 存</el-button>
      </span>
    </el-dialog>
  </div>

    <div>
      <el-dialog title="修改头像" :visible.sync="dialogPhotoVisible" width="40%">
        <el-form :model="photoForm" ref="photoForm" label-width="100px">
          <el-row>
            <el-col :span="20">
              <el-form-item
                label="选择头像："
                prop="photo">
                <el-upload
                  class="avatar-uploader"
                  action="http://localhost:8888/sysUser/data/uploadFile"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                  :on-success="successImgList"
                  :before-upload="beforeAvatarUpload">
                  <img v-if="imgUid.url" :src="imgUid.url" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cacnlPhoto">取 消</el-button>
          <el-button type="primary" @click="subimitPhoto">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
  import persinalApi from "@/api/personal"
  import { getToken } from '@/utils/auth'
  export default {
    name: 'page401',
    data(){
      return{
        uploadHeaders: {
          'user-token':getToken()
        },
        userInfo:{
          nickname:''
        },
        addressInfos:[],
        pickerOptions: {
          disabledDate(time){
            return time.getTime() > Date.now() - 8.64e7
          }
        },
        dialogPhotoVisible:false,
        photoForm:{},
        imgUid:{
          url:'',
        },
        /** 添加地址弹出框 **/
        addressDialogVisible: false,
        /** 地址信息 **/
        addressInfo:{},
        /** 省级地区数据 **/
        province:{},
        provinces:[],
        /** 市级地区数据 **/
        city:{},
        cities:[],
        disabledCity: true,
        /** 县级地区数据 **/
        district:{},
        districts:[],
        disabledDistrict: true,
        /** 乡镇级地区数据 **/
        street:{},
        streets:[],
        disabledStreet: true,
      }
    },
    created(){
      this.initPage();
    },
    methods: {
      initPage() {
        this.userInfo = {};
        persinalApi.initShopUserInfo().then(res => {
          this.userInfo = res.data;
          this.initAddressInfos();
        }).catch(() => {

        })
      },
      initAddressInfos(){
        persinalApi.initAddressInfo().then(res => {
          this.addressInfos = [];
          this.addressInfos = res.data;
        }).catch(() => {

        })
      },
      validateNickname(rule, value, callback){
        const usernameRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
        if (value === '' || typeof(value) == "undefined"){
          callback(new Error('请输入昵称'));
        }
        if (!usernameRegex.test(value)) {
          callback(new Error('昵称只能由常用汉字+英文字母+数字组成'));
        } else {
          callback()
        }
      },
      /** 地址信息收货人名称校验 **/
      validateConsignee(rule, value, callback){
        const usernameRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
        if (value === '' || typeof(value) == "undefined"){
          callback(new Error('请输入联系人名称'));
        }
        if (!usernameRegex.test(value)) {
          callback(new Error('名称只能由常用汉字+英文字母+数字组成'));
        } else {
          callback()
        }
      },
      validateAddressInfo(rule, value, callback){
        const usernameRegex = /^[a-zA-Z0-9_\u4e00-\u9fa5]+$/
        if (value === '' || typeof(value) == "undefined"){
          callback(new Error('请输入详细地址'));
        }
        if (!usernameRegex.test(value)) {
          callback(new Error('详细地址只能由常用汉字+英文字母+数字组成'));
        } else {
          callback()
        }
      },
      /** 地址信息收货人手机号校验 **/
      validateAddressPhone(rule, value, callback){
        const usernameRegex = /^1[34578]\d{9}$/
        if (value === '' || typeof(value) == "undefined"){
          callback(new Error('请输入手机号码'))
        }
        if (!usernameRegex.test(value)) {
          callback(new Error('请输入正确的手机号码'))
        } else {
          callback()
        }
      },
      /** 个人信息修改提交事件 **/
      userInfoSubmit(uaerInfoFormName){
        this.$refs[uaerInfoFormName].validate(valid => {
          if (valid) {
            let params = {
              id: this.userInfo.id,
              nickname: this.userInfo.nickname,
              sex: this.userInfo.sex,
              age: this.userInfo.age
            }
            persinalApi.updateShopUserInfo(params).then(res => {
              this.$notify({title: '成功', message: "修改个人信息成功", type: 'success'});
            }).catch(() => {
              this.$notify.error({title: '失败', message: "个人信息修改失败"});
            })
            return true;
          } else {
            this.$notify({title: '提示', message: '你修改的信息中有不合规信息', type: 'warning'});
          }
        })
      },
      /** 编辑地址按钮事件 **/
      updateAddress(item){
        this.initAddressInfoUtil(item);
        this.addressInfo = item;
        this.addressDialogVisible = true;
      },
      /** 删除地址信息按钮事件 **/
      deleteAddress(item){
        this.$confirm('此操作将删除联系人为“'+item.consignee+'”的地址信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          persinalApi.deleteAddressInfo([item.id]).then(res => {
            this.initAddressInfos();
            this.$notify({title: '成功', message: "成功删除地址信息", type: 'success'});
          }).catch(() => {
            this.$notify.error({title: '失败', message: "地址信息删除失败"});
          })
        }).catch(() => {
          this.$notify.info({title: '消息', message: "取消删除操作"});
        });
      },
      initAddressInfoUtil(item){
        let params = {
          keywords: "100000",
          subdistrict: 1
        }
        this.addressInfo = {};
        this.province = {};
        this.provinces = [];
        this.city = {};
        this.cities = [];
        this.district = {};
        this.districts = [];
        this.street = {};
        this.streets = [];
        this.disabledCity = false;
        this.disabledStreet = false;
        persinalApi.getAddressInfo(params).then(res => {
          this.provinces = res.data.districts[0].districts;
          this.provinces.forEach(value => {
            if (value.adcode === item.province+"") {
              this.province = value;
            }
          })
        }).catch(() => {
          this.$notify({title: '失败', message: "地址信息获取失败", type: 'success'});
        });
        persinalApi.getAddressInfo({ keywords: item.province+"", subdistrict: 1}).then(res => {
          this.cities = res.data.districts[0].districts;
          this.cities.forEach(value => {
            if (value.adcode === item.city+"") {
              this.city = value;
            }
          })
        }).catch(() => {
          this.$notify.error({title: '失败', message: "地址信息获取失败"});
        });
        if (item.district !== 0){
          this.disabledDistrict = false;
          persinalApi.getAddressInfo({ keywords: item.city+"", subdistrict: 1}).then(res => {
            this.districts = res.data.districts[0].districts;
            this.districts.forEach(value => {
              if (value.adcode === item.district+"") {
                this.district = value;
              }
            })
          }).catch(() => {
            this.$notify({title: '失败', message: "地址信息获取失败", type: 'success'});
          });
          persinalApi.getAddressInfo({ keywords: item.district+"", subdistrict: 1}).then(res => {
            this.streets = res.data.districts[0].districts;
            this.streets.forEach(value => {
              if (value.name === item.streetName+"") {
                this.street = value;
              }
            })
          }).catch(() => {
            this.$notify({title: '失败', message: "地址信息获取失败", type: 'success'});
          });
        } else {
          this.disabledDistrict = true;
          persinalApi.getAddressInfo({ keywords: item.city+"", subdistrict: 1}).then(res => {
            this.streets = res.data.districts[0].districts;
            this.streets.forEach(value => {
              if (value.name === item.streetName+"") {
                this.street = value;
              }
            })
          }).catch(() => {
            this.$notify({title: '失败', message: "地址信息获取失败", type: 'success'});
          });
        }
      },
      /** 添加地址按钮事件 **/
      addressInfoAdd(){
        let params = {
          keywords: "100000",
          subdistrict: 1
        }
        this.addressInfo = {};
        this.province = {};
        this.provinces = [];
        this.city = {};
        this.cities = [];
        this.district = {};
        this.districts = [];
        this.street = {};
        this.streets = [];
        this.disabledCity = true;
        this.disabledDistrict = true;
        this.disabledStreet = true;
        persinalApi.getAddressInfo(params).then(res => {
          this.addressDialogVisible = true;
          this.provinces = res.data.districts[0].districts;
        }).catch(() => {
          this.$notify({title: '失败', message: "地址信息获取失败", type: 'success'});
        });
      },
      /** 关闭地址添加弹出框 **/
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      addressSelectStruts(level, data){
        /** 状态赋值初始化 **/
        if (level == "province"){
          this.provinces = data;
        } else if (level == "city"){
          this.cities = data;
          this.disabledCity = false;
        } else if (level == "district"){
          this.districts = data;
          this.disabledDistrict = false;
        } else if (level == "street"){
          this.streets = data;
          this.disabledStreet = false;
        }
      },
      addressSelectInitStruts(level){
        /** 状态清理旧值 **/
        let levelCode = 0
        switch (level) {
          case 1:
            this.city = {};
            this.cities = [];
            this.district = {};
            this.districts = [];
            this.street = {};
            this.streets = [];
            this.disabledCity = true;
            this.disabledDistrict = true;
            this.disabledStreet = true;
            levelCode = this.province.adcode;
            break;
          case 2:
            this.district = {};
            this.districts = [];
            this.street = {};
            this.streets = [];
            this.disabledDistrict = true;
            this.disabledStreet = true;
            levelCode = this.city.adcode;
            break;
          case 3:
            this.street = {};
            this.streets = [];
            this.disabledStreet = true;
            levelCode = this.district.adcode
            break;
          case 4:
            levelCode = this.streets.adcode;
            break;
        }
        return levelCode;
      },
      /** 选择地区事件 **/
      changeAddress(level){
        if (level<1 || level > 3){
          /** 街道级别没有下级就直接返回 **/
          return true;
        }
        let params = {
          keywords: this.addressSelectInitStruts(level),
          subdistrict: 1
        }
        persinalApi.getAddressInfo(params).then(res => {
          this.addressSelectStruts(res.data.districts[0].districts[0].level, res.data.districts[0].districts);
          return true;
        }).catch(() => {
          this.$notify.error({title: '失败', message: "地址信息获取失败"});
        });
      },
      /** 地区信息保存事件 **/
      addressInfoSave(){
        // console.log(this.addressInfo);
        // console.log(this.province);
        // console.log(this.city);
        // console.log(this.district);
        // console.log(this.street);
        if (typeof(this.street.adcode) === "undefined" || this.street.adcode === ""){
          this.$notify({title: '提示', message: "地址信息请选择到乡镇级", type: 'warning'});
          return false;
        }
        this.$refs['addressInfo'].validate(valid => {
          if (valid) {
            let params = {
              id: typeof(this.addressInfo.id)=="undefined"?null:this.addressInfo.id,
              consignee: this.addressInfo.consignee,
              phone: this.addressInfo.phone,
              address: this.addressInfo.address,
              province: this.province.adcode,
              provinceName: this.province.name,
              city: this.city.adcode,
              cityName: this.city.name,
              district: typeof(this.district.adcode)=="undefined"?null:this.district.adcode,
              districtName: typeof(this.district.adcode)=="undefined"?null:this.district.name,
              street: this.street.adcode,
              streetName: this.street.name
            }
            persinalApi.saveAddressInfo(params).then(res => {
              if (res.code === 1){
                this.initAddressInfos();
                this.userInfo = res.data;
                this.$notify({title: '成功', message: "收货地址信息保存成功", type: 'success'});
                this.addressDialogVisible = false;
              }
            }).catch(() => {
              this.$notify.error({title: '失败', message: "地址信息获取失败"});
              return false;
            })
          } else {
            this.$notify({title: '提示', message: "输入的信息不合规", type: 'warning'});
          }
        })
      },
      /** 头像修改开始 **/
      successImgList(response, file, fileList){
        this.imgUid = {
          uid: file.uid,
          name: file.name,
          url: response.data[file.name]
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt1M = file.size / 1024 / 1024 < 2;
        this.beforeUploadImgRule(isJPG,"JPG",isLt1M,"2MB")
        return isJPG && isLt1M;
      },
      updatePhoto(){
        this.imgUid = {url:'',}
        this.dialogPhotoVisible = true;
      },
      cacnlPhoto(){
        this.dialogPhotoVisible = false;
        this.imgUid = {url:'',}
      },
      subimitPhoto(){
        if (this.imgUid.url===''){
          this.$notify.warning({title:'提示', message:'上传图片！'});
          return false;
        }
        let params = {
          id: this.userInfo.id,
          photo: this.imgUid.url,
        }
        persinalApi.updateShopUserInfo(params).then(res => {
          this.dialogPhotoVisible = false;
          this.$notify.success({title:'成功', message:'头像重置成功！'});
          this.imgUid = {url:'',}
          this.initPage();
        }).catch(() => {
          this.$notify.error({title:'错误', message:'系统繁忙，请稍后再试！'});
        })

      },
      /** 规则校验 **/
      beforeUploadImgRule(isFormat,formatValue, isLt, ltValue){
        // 图片格式、大小规则检验
        if (!isFormat) {
          this.$message.error('上传图片只能是 '+formatValue+' 格式!')
        }
        if (!isLt) {
          this.$message.error('上传图片大小不能超过 '+ltValue+'!')
        }
      },
      valueLengthRule(value, name, maxlength){
        if (value.length > maxlength){
          return new Error(name + '不能超过'+ maxlength +'个字')
        }
      },
    },
  }
</script>
<style>
/*标题*/
.licc-personal-content-row{
  width: 100%;
  margin-top: 20px;
}
.licc-center-title{
  text-align: left;
  line-height: 50px;
}
.licc-center-title em{
  letter-spacing: 2px;
  font-size: 16px;
  padding-left: 20px;
}
/*内容*/
.licc-personal-info-top{
  width: 100%;
  height: 30px;
  line-height: 30px;
}
.licc-personal-info-title{
  width: 50px;
  float: left;
  padding: 20px 10px 20px 10px;
}
.licc-personal-info-title em{
  font-size: 14px;
}
.licc-personal-info-value{
  float: left;
  padding: 20px 10px 20px 10px;
}
.licc-personal-info-value>.el-icon-edit {
  cursor: pointer;
}
.licc-personal-info-value>.el-icon-edit:hover{
  color: #ff0000;
}
.licc-personal-info-image-update{
  cursor: pointer;
  font-size: 12px;
  color: rgb(153, 153, 153);
}
.licc-personal-info-image-update:hover{
  color: #ff0000;
}
/***地址**/
.licc-personal-address{
  margin-top: 10px;
}
.licc-personal-address-consignee{
  width: 150px;
  height: 25px;
  line-height: 25px;
  padding-left: 20px;
  text-align: left;
  float: left;
  overflow: hidden;
}
.licc-personal-address-phone{
  width: 180px;
  height: 25px;
  line-height: 25px;
  padding-left: 20px;
  text-align: left;
  float: left;
}
.licc-personal-address-click{
  width: 150px;
  height: 25px;
  line-height: 25px;
  padding-left: 10px;
  padding-right: 20px;
  text-align: right;
  float: left;
}
.licc-personal-address-click>.el-icon-edit{
  cursor: pointer;
}
.licc-personal-address-click>.el-icon-delete{
  cursor: pointer;
}
.licc-personal-address-click>.el-icon-edit:hover{
  color: red;
}
.licc-personal-address-click>.el-icon-delete:hover{
  color: red;
}
.licc-personal-address-info{
  width: 520px;
  height: 20px;
  line-height: 20px;
  text-align: left;
  font-size: 12px;
  padding-left: 20px;
  padding-right: 10px;
  overflow: hidden;
  border-bottom: 1px solid #DCDFE6;
}


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
